<?
/*
Plugin Name: Amazon Info Grabber (wp-amazoninfo)
Plugin URI: http://ollyjackson.co.uk/projects/amazonplugin/
Description: Blah, blah.
Author: Oliver Jackson
Version: 0.1
Author URI: http://ollyjackson.co.uk
*/

/* Set developer token */
global $accesskey;
$accesskey="YOUR KEY HERE";
global $table_prefix, $wpdb;
global $table_name;
$table_name = $table_prefix . "amazoninfo";

function startElementHandlerAmazon ($parser,$name, $attribs){
        global $state;
        $state=$name;
        /*if ($name=="ITEMATTRIBUTES") {
                $resultdata[$resultcount]["AUTHOR"] = $attribs["AUTHOR"];
                $resultdata[$resultcount]["TITLE"] = $attribs["TITLE"];
        }*/
}

function endElementHandlerAmazon ($parser,$name){
        global $resultcount;
        global $state;
        $state="";
        if ($name=="ITEMATTRIBUTES") $resultcount++;
}

function characterDataHandlerAmazon ($parser, $data) {
        global $resultdata;
        global $state;
        if ($state=="TITLE") { $resultdata["title"] = $data; }
        if ($state=="AUTHOR") { $resultdata["author"] = $data; }
}


function amazoninfo_get_title($title) {
        global $accesskey;
        global $resultdata;
        global $wp_query;
        global $wpdb;
        global $table_name;
        
				$post=$wp_query->post;
        $post_id=$post->ID;
        $amazon_asin=get_post_meta($post_id, 'AMAZON_ASIN', true );
       	
       	
       	
       	
	// do we actually have an ASIN on this post?
	if ($amazon_asin) {
					$query="select * from ".$table_name." where asin='".$amazon_asin."'";
					$results = $wpdb->query( $query );
					
					if ($results > 0 ) {
						$title=$wpdb->get_var("SELECT title FROM ".$table_name." WHERE asin='".$amazon_asin."'");
						$author=$wpdb->get_var("SELECT author FROM ".$table_name." WHERE asin='".$amazon_asin."'");
						return $title." by ".$author;
					}
					else {
					$url="http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=$accesskey&Operation=ItemLookup&ItemId=$amazon_asin";
        	if (!($fp=@fopen($url, "r")))
                	die ("Couldn't open XML URL");
	        if (!($xml_parser = xml_parser_create()))
        	        die("Couldn't create parser.");

	        $resultcount=0;
        	$resultdata=array();
	        $state="";

        	xml_set_element_handler($xml_parser,"startElementHandlerAmazon","endElementHandlerAmazon");
	        xml_set_character_data_handler( $xml_parser, "characterDataHandlerAmazon");

        	while( $data = fread($fp, 4096)){
                	if(!xml_parse($xml_parser, $data, feof($fp))) {
                        	break;
	                }
        	}
	        xml_parser_free($xml_parser);
        	fclose($fp);
	        for ($i = 0; $i < count($resultdata); $i++) {
	        	$query = "INSERT INTO ".$table_name." (asin,title,author) VALUES ('".$amazon_asin."','".$wpdb->escape($resultdata["title"])."','".$wpdb->escape($resultdata["author"])."')";
						$results = $wpdb->query( $query );
        	  return $resultdata["title"]." by ".$resultdata["author"];
	        }
	      }
	}
	// we don't, so just use the current title
	else {
		return $title;
	}
	

}

function amazoninfo_install () {
	global $wpdb;
	global $table_name;
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
      $sql = "CREATE TABLE ".$table_name." (
	      asin VARCHAR(10) NOT NULL,
				title VARCHAR(200) NOT NULL,
	      author VARCHAR(200) NOT NULL
	     );";

      require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
      dbDelta($sql);
   }

}



add_action('activate_amazon/amazon.php','amazoninfo_install');
add_filter('the_title', 'amazoninfo_get_title');
?>
